<template>
  <div class="layout">
    <a
      @click="contact"
      style="float: right; margin-right: 50px; font-size: 12px"
      >联系作者:929226676@qq.com</a
    >
    <div class="layout-header">
      <Form :model="searchModel" label-position="left" :label-width="100">
        <Form-item>
          <Select
            v-model="searchModel.type"
            default-label="篮球场"
            style="width: 100px"
          >
            <Option v-for="item in typeList" :value="item" :key="item">{{
              item
            }}</Option>
          </Select> 
          <Select
            v-model="searchModel.sheng"
            placeholder="省"
            clearable
            style="width: 150px"
          >
            <Option
              v-for="items in addressOptions"
              :value="items.name"
              :key="items.id"
              @click.native="optionsChangeProvince(items.name)"
              >{{ items.name }}</Option
            >
          </Select>
          <Select
            v-model="searchModel.shi"
            placeholder="市"
            clearable
            style="width: 150px"
          >
            <Option
              v-for="o in cityOptions"
              :value="o.name"
              :key="o.id"
              @click.native="optionsChangeCity(o.name)"
              >{{ o.name }}</Option
            >
          </Select>
          <Select
            v-model="searchModel.xian"
            placeholder="县"
            clearable
            style="width: 150px"
          >
            <Option
              v-for="o in countiesOptions"
              :value="o.name"
              :key="o.id"
              @click.native="optionsChangeCounties(o.name)"
              >{{ o.name }}</Option
            >
          </Select>
          <Button type="primary" @click="getData()">搜索</Button>
          <Button type="primary" @click="draw()">我要添加</Button>
        </Form-item>
      </Form>
      <AddModal
        ref="addModal"
        @on-ok="getData"
        @on-cancel="clearMarker"
      ></AddModal>
      <ContactModal ref="contactModal"></ContactModal>
      <MailModal ref="mailModal"></MailModal>
      <div v-show="false">
        <PopupWrap ref="popup_detail" :value="info">
          <template #default="m">
            <div class="base-popup">
              <h2>
                {{ m.name }}
                <a
                  v-if="m.show"
                  @click="update(m)"
                  style="font-size: 12px; margin-left: 10px"
                  >[修改]</a
                >
                <a
                  v-else
                  @click="report(m)"
                  style="font-size: 12px; margin-left: 10px"
                  >[举报]</a
                >
              </h2>
            </div>
            <div class="popup-wrap-body">
              <p>
                <span>球场类型</span>:<span>{{ m.type }}</span>
              </p>
              <p>
                <span>室内室外</span>:<span>{{ m.snsw }}</span>
              </p>
              <p>
                <span>是否收费</span>:<span>{{ m.mfsf }}</span>
              </p>
              <p v-if="m.mfsf == '收费'">
                <span>收费标准</span>:<span>{{ m.sfbz }}</span>
              </p>
              <p>
                <span>场地电话</span>:<span>{{ m.cgdh }}</span>
              </p>
              <p>
                <span>开放时间</span>:<span>{{ m.kssj }}-{{ m.jssj }}</span>
              </p>
              <p>
                <span>球场地址</span>:<span>{{ m.dizhi }}</span>
              </p>
            </div>
          </template>
        </PopupWrap>
      </div>
    </div>
    <div class="layout-body">
      <div id="map" :style="mapStyle"></div>
    </div>
  </div>
</template>
<script>
import { LMap, LTileLayer, LMarker, LPopup } from "vue2-leaflet";
import L from "leaflet";
import leafletDraw from "leaflet-draw";
import AddModal from "./components/addModal.vue";
import ContactModal from "./components/contactModal.vue";
import MailModal from "./components/mailModal.vue";
import { provice } from "../js/city";
export default {
  name: "VueLeaflet.vue",
  components: {
    LMap,
    LTileLayer,
    LMarker,
    LPopup,
    AddModal,
    ContactModal,
    MailModal,
    PopupWrap: () => import("./components/popupWrap"),
  },
  data() {
    return {
      swap: {
        $mapContainer: null, //map地图对象
        $labelLayer: null, //现有marker点位集合
        $drawnItems: null, //新画的marker layer
        $sessionid: null, //新画的marker layer
        $popup: null, //新画的marker layer
      },
      center:[39.904, 116.408],
      searchModel: {
        sheng: null, //省
        shi: null, //市
        xian: null, //区
        type: "篮球场",
      },
      model: {
        // sheng: "北京", //省
        // shi: "北京", //市
        // xian: null, //区
        mfsf: "免费",
        snsw: "室外",
        kfsj: ["08:30", "22:00"],
        lat: null,
        lng: null,
        sessionid: null,
        type: "篮球场",
      },
      info: {},//popup详情
      addressOptions: [], //城市三级联动数据
      cityOptions: [], //市
      countiesOptions: [], //县/区
      typeList: ["篮球场", "足球场", "羽毛球场", "网球场", "乒乓球场"], //场地类型
      mapStyle:null,
    };
  },
  mounted() {
    this.addressOptions = provice;
    this.model.sessionid = sessionStorage.getItem('sessionid');
    if (this.model.sessionid == null) {
      this.model.sessionid = this.getKey();
      sessionStorage.setItem('sessionid', this.model.sessionid);
      // this.$refs.mailModal.show();
    }
    this.$nextTick(() => {
      this.initMap();
    });
    let h = window.innerHeight -110 + 'px';
    this.mapStyle = {
      width:'100vw',
      height:h
    }
  },
  //网站seo优化
  metaInfo: {
    title:
      "去哪打球_哪有篮球场,哪有羽毛球场,哪有足球场,哪有乒乓球场,哪有网球场,找场地就到去哪打球网",
    meta: [
      {
        name: "篮球场",
        content: "篮球场地,去哪打球,哪有篮球场,篮球场",
      },
      {
        name: "足球场",
        content: "足球场地,去哪踢球,哪有足球场,足球场",
      },
      {
        name: "羽毛球场",
        content: "羽毛球场地,去哪打球,哪有羽毛球场,羽毛球场",
      },
      {
        name: "网球场",
        content: "网球场地,去哪打网球,哪有网球场,网球场",
      },
      {
        name: "乒乓球场",
        content: "乒乓球场地,去哪打乒乓球,哪有乒乓球场,乒乓球场",
      },
      {
        name: "打篮球",
        content: "篮球场地,去哪打球,哪有篮球场,篮球场",
      },
    ],
  },
  methods: {
    //选取省份时的事件
    optionsChangeProvince(e) {
      let _this = this;
      let item;
      _this.addressOptions.forEach((ele, i) => {
        if (ele.name === e) {
          //将选取的省份到省份里去比对，有值则给到当前item
          item = ele;
        }
        if (item) {
          this.cityOptions = item.city; // 将选中item的城市名称给cityOption
          this.model.xian = null; //这两步是用来当市区发生变化时置空县/区
          this.countiesOptions = [];
        }
      });
    },
    //选取城市时的事件
    optionsChangeCity(e) {
      let _this = this;
      if (!_this.cityOptions) {
        //这一步是用来判断是否存在市区，否则不让其遍历
        return;
      }
      _this.cityOptions.forEach((ele, i) => {
        if (ele.name === e) {
          this.model.shi = ele.name;
          this.model.lat = ele.lat;
          this.model.lng = ele.lng;
          this.countiesOptions = ele.districtAndCounty; // 将选中item的矿机批次给batchNumList
        }
      });
    },
    //选取县/区时的事件
    optionsChangeCounties(e) {
     let _this = this;
      if (!_this.countiesOptions) {
        return;
      }
      _this.countiesOptions.forEach((ele, i) => {
        if (ele.name === e) {
          this.model.xian = ele.name;
          this.model.lat = ele.lat;
          this.model.lng = ele.lng;
        }
      });
    },
    initMap() {
      var _this = this;
      this.swap.$mapContainer = L.map("map", {
        center: this.center, // 地图中心
        zoom: 12, //缩放比列
        attributionControl: false, // 移除右下角leaflet标识
      });
      L.tileLayer(
        "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}"
      ).addTo(this.swap.$mapContainer);
      this.swap.$drawnItems = new L.FeatureGroup();
      this.swap.$mapContainer.addLayer(this.swap.$drawnItems);
      //增加点完成后
      this.swap.$mapContainer.on(L.Draw.Event.CREATED, function (event) {
        var layer = event.layer;
        _this.swap.$drawnItems.addLayer(layer);
        let latLng = layer.getLatLng();
        _this.model.lat = latLng.lat;
        _this.model.lng = latLng.lng;
        if (_this.searchModel.shi) {
          _this.model.sheng = _this.searchModel.sheng;
          _this.model.shi = _this.searchModel.shi;
          _this.model.xian = _this.searchModel.xian;
          _this.model.type = _this.searchModel.type;
        }
        _this.initModel();
        _this.$refs.addModal.show(_this.model);
      });
      this.getLocation();
    },
    //初始化已有点位的图层
    async initLabelLayer() {
      if (this.swap.$labelLayer != null) {
        this.swap.$labelLayer.clearLayers();
      }
      this.swap.$labelLayer = new L.LayerGroup();
      this.swap.$labelLayer.addTo(this.swap.$mapContainer);
    },
    initModel() {
      this.model.id = null;
      this.model.name = "";
      this.model.sfbz = "";
      this.model.cgdh = "";
      this.model.kfsj = ["08:30", "22:00"];
    },
    clearMarker() {
      this.swap.$drawnItems.clearLayers();
    },
    //我要添加
    draw() {
      new L.Draw.Marker(
        this.swap.$mapContainer
      ).enable();
    },
    //获取点位数据
    getData() {
      if (!this.searchModel.sheng || !this.searchModel.shi) {
        this.$Message.info("大兄弟,数据量太大了,至少选择一下省市欸~");
        return;
      }
      this.swap.$mapContainer.setView([this.model.lat, this.model.lng], 12);
      var _this = this;
      this.clearMarker();
      this.initLabelLayer();
      var myIcon = {};
      this.$axios.post("api/changdi/getAll", this.searchModel).then((res) => {
        res.data.map((i) => {
          if(i.mfsf == "收费"){
            myIcon = L.icon({
              iconSize: [25, 41],
              iconAnchor: [12, 20],
              iconUrl: require('@/assets/addr1.png'),
            });
          }else{
            myIcon = L.icon({
              iconSize: [25, 41],
              iconAnchor: [12, 20],
              iconUrl: require('@/assets/addr.png'),
            });
          }

          L.marker([i.lat, i.lng], {
            icon:myIcon,
            title: i.name,
          })
            .addTo(this.swap.$labelLayer)
            .on("click", function (e) {
              _this.handleMapMarerClick(i);
            })
            .on("dragend", function (ee) {
              //只能拖拽自己添加的点
              if (i.sessionid == _this.model.sessionid) {
                i.lat = ee.target.getLatLng().lat;
                i.lng = ee.target.getLatLng().lng;
                //拖拽结束后更新点位经纬度
                _this.$axios.post("api/changdi/update", i).then((res) => {
                  _this.$Message.success({
                    content: "场地位置已更新!",
                    duration: 2,
                  });
                });
              } else {
                //复原marker位置
                this.setLatLng([i.lat, i.lng]);
                _this.$Message.warning({
                  content: "只能修改本次你添加的场地!",
                  duration: 2,
                });
              }
            })
            .dragging.enable();
        });
      });
    },
    //显示popul详情
    handleMapMarerClick(item) {
      this.info = item;
      this.info.show = false;
      if (this.model.sessionid == this.info.sessionid) {
        this.info.show = true;
      }
      let content = this.$refs["popup_detail"].$el;
      let kuan_name = this.info.name.length * 20 + 40 > 160
          ? this.info.name.length * 20 + 40
          : 160;
      let kuan_cgdh = (this.info.cgdh.length + 5) * 10;
      let lth = kuan_name>kuan_cgdh?kuan_name:kuan_cgdh;
      this.swap.$popup = L.popup({ minWidth: lth, maxWidth: lth })
        .setLatLng([item.lat, item.lng])
        .setContent(content)
        .openOn(this.swap.$mapContainer);
    },
    //获取本次操作的sessionkey
    getKey() {
      this.$axios.post("api/changdi/getKey").then((res) => {
        return res.data;
      });
    },
    //定位用户位置
    async getLocation() {
      await this.$axios.post("https://restapi.amap.com/v3/ip?output=xml&key=5aeb0c87687eff78f5dd75af2f90c929").then((res) => {
        if(res.data != null){
          this.searchModel.sheng = res.data.province.replace("省","");
          this.searchModel.shi = res.data.city.replace("市","");
          this.optionsChangeProvince(this.searchModel.sheng);
          this.optionsChangeCity(this.searchModel.shi);
        }
      });
      this.getData();
    },
    //修改场地内容
    update(m) {
      this.swap.$mapContainer.closePopup(this.swap.$popup);
      if (m.sessionid != this.model.sessionid) {
        this.$Message.warning({
          content: "只能修改本次你添加的场地!",
          duration: 2,
        });
        return;
      }
      m.kfsj = [m.kssj, m.jssj];
      this.$refs.addModal.show(m);
    },
    //举报错误信息
    report(m) {
      let jubao = {
        changdiId:m.id,
      };
      this.$Modal.confirm({
        title: "错误信息举报",
        onOk: () => {
          this.$axios.post("api/jubao/add",jubao).then((res) => {
            this.$Message.success({
              content: "感谢大兄弟,等我查看后删了他!",
              duration: 2,
            });
            this.swap.$mapContainer.closePopup(this.swap.$popup);
          });
        },
        render: (h) => {
          return h("Input", {
            props: {
              type:'textarea',
              rows:6,
              maxlength:'200',
              value: jubao.content,
              autofocus: true,
              placeholder:'大兄弟，描述一下球场错误信息，等我验证了删了他！'
            },
            on: {
              input: (val) => {
                jubao.content = val;
              },
            },
          });
        },
      });
    },
    contact() {
      this.$refs.contactModal.show();
    },
  },
};
</script>
<style lang="less" scoped>
.popup-wrap-body {
  > p {
    margin: 2px 0;
    > span {
      font-size: 14px;
      margin: 0 3px;
      min-width: 100px;
    }
  }
}
.layout {
  margin-top: 20px;
  position: relative;
  border-radius: 4px;
  overflow: hidden;
}
.layout-header {
  text-align: left;
  height: 60px;
}
.layout-body {
  text-align: center;
  min-height: 200px;
  margin: 15px;
  overflow: hidden;
}
</style>
